package org.chen.ctrip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.common.ctrip.entity.CustomDayContent;
import org.chen.ctrip.mapper.CustomDayContentMapper;
import org.chen.ctrip.service.CustomDayContentService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class CustomDayContentServiceImpl extends ServiceImpl<CustomDayContentMapper, CustomDayContent> 
        implements CustomDayContentService {

    @Override
    public CustomDayContent getMatchingContent(String platform, String dayType, 
                                             String departureCity, String destinationCity) {
        // 按优先级查找：完全匹配 > 城市匹配 > 平台默认
        
        // 1. 完全匹配
        CustomDayContent exactMatch = baseMapper.findMatchingContent(
            platform, dayType, departureCity, destinationCity);
        if (exactMatch != null && exactMatch.getEnabled()) {
            return exactMatch;
        }
        
        // 2. 城市匹配（忽略天数）
        QueryWrapper<CustomDayContent> cityWrapper = new QueryWrapper<>();
        cityWrapper.eq("platform", platform)
                  .eq("day_type", dayType)
                  .eq("departure_city", departureCity)
                  .eq("destination_city", destinationCity)
                  .eq("enabled", true)
                  .orderByDesc("create_time")
                  .last("LIMIT 1");
        
        CustomDayContent cityMatch = getOne(cityWrapper);
        if (cityMatch != null) {
            return cityMatch;
        }
        
        // 3. 平台默认（通用模板）
        QueryWrapper<CustomDayContent> defaultWrapper = new QueryWrapper<>();
        defaultWrapper.eq("platform", platform)
                     .eq("day_type", dayType)
                     .eq("departure_city", "")
                     .eq("destination_city", "")
                     .eq("enabled", true)
                     .orderByDesc("create_time")
                     .last("LIMIT 1");

        return getOne(defaultWrapper);
    }

    @Override
    public List<CustomDayContent> getContentByPlatform(String platform) {
        QueryWrapper<CustomDayContent> wrapper = new QueryWrapper<>();
        wrapper.eq("platform", platform)
               .orderByDesc("create_time");
        return list(wrapper);
    }

    @Override
    public CustomDayContent saveOrUpdateContent(CustomDayContent content) {
        if (content.getId() == null) {
            content.setId(UUID.randomUUID().toString());
            content.setCreateTime(LocalDateTime.now());
        }
        content.setUpdateTime(LocalDateTime.now());
        saveOrUpdate(content);
        return content;
    }
}